package cn.edu.abtu.service.impl;

import cn.edu.abtu.entity.SysUser;
import cn.edu.abtu.service.SysUserService;
import cn.edu.abtu.mapper.SysUserMapper;
import cn.edu.abtu.utils.AjaxResult;
import cn.edu.abtu.utils.SystemConstants;
import cn.edu.abtu.vo.query.UserQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * (SysUser)表服务实现类
 *
 * @author makejava
 * @since 2022-11-16 11:48:22
 */
@Slf4j
@Service
@Transactional
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private FileServiceImpl fileService;

    // 根据用户名查询用户信息
    @Override
    public SysUser getUserByUsername(String username) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return sysUserMapper.selectOne(queryWrapper);
    }

    @Override
    public AjaxResult page(UserQueryVo userQueryVo) {
        Page<SysUser> pageInfo = new Page<>(userQueryVo.getPageNum(), userQueryVo.getPageSize());
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        // 部门编号
        queryWrapper.eq(Objects.nonNull(userQueryVo.getDepartmentId()), "department_id", userQueryVo.getDepartmentId());
        // 用户名
        queryWrapper.like(Objects.nonNull(userQueryVo.getUsername()), "username", userQueryVo.getUsername());
        // 真实姓名
        queryWrapper.like(Objects.nonNull(userQueryVo.getRealName()), "real_name", userQueryVo.getRealName());
        // 电话
        queryWrapper.like(Objects.nonNull(userQueryVo.getPhone()), "phone", userQueryVo.getPhone());
        sysUserMapper.selectPage(pageInfo, queryWrapper);
        return AjaxResult.success("查询成功!", pageInfo);
    }

    @Override
    public boolean deleteById(Long id) {
        SysUser user = sysUserMapper.selectById(id);
        if (Objects.nonNull(user)){
            boolean result = sysUserMapper.deleteUserRole(id);
            if (result){
                int i = sysUserMapper.deleteById(id);
                if (Objects.nonNull(user.getAvatar()) && !user.getAvatar().equals(SystemConstants.DEFAULT_AVATAR)){
                    fileService.deleteFile(user.getAvatar());
                }
                return true;
            }
        }
        return false;
    }
}
